from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.backends import default_backend
import base64


def encrypt_message(public_key_pem: str, message: str) -> str:
    """使用 RSA 公钥加密消息"""
    # 加载公钥
    public_key = serialization.load_pem_public_key(
        public_key_pem.encode(), backend=default_backend()
    )

    # # 加密数据,随机加盐
    # encrypted = public_key.encrypt(
    #     message.encode(),
    #     padding.OAEP(
    #         mgf=padding.MGF1(algorithm=hashes.SHA256()),
    #         algorithm=hashes.SHA256(),
    #         label=None
    #     )
    # )
    #
    # 加密数据（使用 PKCS1v1.5，无随机填充）
    encrypted = public_key.encrypt(
        message.encode(),
        padding.PKCS1v15()
    )

    # 返回 Base64 编码后的密文
    return base64.b64encode(encrypted).decode()



if __name__ == '__main__':

    # 示例公钥（请替换为你的公钥字符串）
    const_publicKey =  (
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl9qVBvCFEzcOk6zRyduv"
        "/AxqI9O0zfiyJle10BkYpi1M4j6l1xHJ1N2+H6NZxrC8Ex5hLN5WngACW0tfpYsB"
        "je+WiDSmENHyjp2hEPN0oNm7Vui1YsukWFeMbYbDKfBwyYnpnXDrYTtRUuiS4y8k"
        "2KgIOEnysSgOuqFykDAvif8qrpn3T2ETQcAR0iTq3oG4x0McguZ7GHGBVrfUGXug"
        "yzQtzGYd2P9lLCwfXtnkZtOjJgBLVw9vl69//5ym2KspwSTSER4uI2GvL2bVhsln"
        "wJuPkslvB7/rHJyYN9ZGNiQVIka9daldr+pqJSN5Mq41xgbYGyjS+7O4ry0jqqek"
        "yQIDAQAB"
    )
    public_key_pem = f"""-----BEGIN PUBLIC KEY-----
    {const_publicKey}
    -----END PUBLIC KEY-----"""
    # 加密示例
    message = "Admin123."
    ciphertext = encrypt_message(public_key_pem, message)
    print("Encrypted:", ciphertext)